package com.alt.base;

import java.util.Stack;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.alt.shared.onImageSet;
import com.alt.utils.ALTSysUtils;

public class ALTTabGroup extends ActivityGroup {

	private Stack<String> stack;
	private boolean finishFromChild = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (stack == null)
			stack = new Stack<String>();
	}

	@Override
	public void finishFromChild(Activity child) {
		Log.i("ALTTabGroup", "finishFromChild:"
				+ child.getClass().getSimpleName());
		finishFromChild = true;
		pop();
	}

	@Override
	public void onBackPressed() {
		Log.i("ALTTabGroup", "onBackPressed");
		onBack();

		finishFromChild = false;
	}

	public void push(String id, Intent intent) {
		Window window = getLocalActivityManager().startActivity(id,
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		if (window != null) {
			stack.push(id);
			setContentView(window.getDecorView());
		}

	}

	public void pop() {
		if (stack.size() < 1) {
			finish();
			return;
		}
		LocalActivityManager manager = getLocalActivityManager();

		// LocalActivityManager manager = getLocalActivityManager();
		manager.destroyActivity(stack.pop(), true);
		if (stack.size() > 0) {
			Activity av = manager.getActivity(stack.peek());
			if (av != null) {
				Intent lastIntent = av.getIntent();
				Window newWindow = manager.startActivity(stack.peek(), lastIntent);				
				setContentView(newWindow.getDecorView());
			}			
		}
	}

	public void onBack() {
		Log.i("ALTTabGroup", "onBack:" + stack.size());

		if (stack.size() < 1) {
			finish();
			return;
		}

		if (finishFromChild) {
			return;
		}

		LocalActivityManager manager = getLocalActivityManager();
		manager.getActivity(stack.peek()).onBackPressed();
	}

	public void popAll() {
		popAll(0);
	}

	public void popAll(int remainUI) {
		LocalActivityManager manager = getLocalActivityManager();

		while (stack.size() > remainUI + 1) {
			manager.destroyActivity(stack.pop(), true);
		}
	}

	// Progress dialog
	final public int PROGRESS_DIALOG = 0;
	AlertDialog progressDialog;

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case (PROGRESS_DIALOG):
			progressDialog = ALTSysUtils.createProgressDialog(this);
			return progressDialog;
		}

		return null;
	}

}
